﻿
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace HandleExcel
{
    public class Log
    {

        private static StreamWriter stream;
        private static string exepath = Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().GetName().CodeBase).Substring(6);
        private static string logpath = (exepath + @"\log\");




        public static void DelateLog()
        {

            if (!Directory.Exists(logpath))
            {
                Directory.CreateDirectory(logpath);
            }
            DirectoryInfo folder = new DirectoryInfo(logpath);
            foreach (FileInfo file in folder.GetFiles())
            {
                if ((DateTime.Now - file.LastWriteTime).Days > 90)
                {
                    File.Delete(file.FullName);
                }
            }

        }


        public static void WriteLog(string fileextname, string logtext)
        {
            try
            {
                if (!Directory.Exists(logpath))
                {
                    Directory.CreateDirectory(logpath);
                }
                string path = logpath + DateTime.Now.ToString("yyyy-MM-dd") + fileextname + ".log";
                Console.WriteLine(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "--" + logtext);
                if (!File.Exists(path))
                {
                    new FileStream(path, FileMode.Create).Close();
                }
                if (File.Exists(path))
                {
                    try
                    {
                        stream = new StreamWriter(path, true);
                        stream.WriteLine(DateTime.Now.ToString() + " " + logtext);
                        stream.WriteLine("--------------------------------------------------------");
                        stream.Close();
                    }
                    catch (Exception e)
                    {
                        stream.Close();
                    }
                }
                else
                {
                    Console.WriteLine("log.txt文件丢失，请重启程序。");
                }
            }
            catch (Exception e)
            {

            }
        }
    }
}
